package com.globant.scrollbar;

import java.lang.ref.WeakReference;
import java.util.Map;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

public class AsyncProcess extends AsyncTask<Void, Integer, Integer> {
	
	private int mProgressStatus = 0;
	private MainActivity mainActivity;
		
	public AsyncProcess(WeakReference<Map<String, Activity>> activityMap) {
		
		if(activityMap != null && activityMap.get().containsKey(BusinessSettings.MAIN_ACTIVITY)){
			this.mainActivity = (MainActivity) activityMap.get().get(BusinessSettings.MAIN_ACTIVITY);
		}
	}

	protected void onPreExecute() {
		mProgressStatus = 0;
	}
	
	@Override
	protected Integer doInBackground(Void... params) {
		if(mainActivity != null) {
			while (mProgressStatus < 100) {
				 mProgressStatus = mProgressStatus + 1;
			
				try {
					Thread.sleep(100L);
					publishProgress(mProgressStatus);
				} catch (InterruptedException e) {
					Log.d("Error", "Error in the application", e);
				}
			}
		}
		return null;
	}
	
	protected void onProgressUpdate(Integer... progress) {
		if(mainActivity != null) {
			mainActivity.getProgressBar().setProgress(progress[0]);
			mainActivity.getProgress().setText(String.valueOf(progress[0]).concat("%"));
		}
	}

	protected void onPostExecute(Integer progress) {
		if(mainActivity != null && mainActivity.hasWindowFocus()) {
			mainActivity.generateToastMessage();
		} else if(mainActivity != null) {
			mainActivity.triggerNotification();
		}
	}
}
